const mongoose = require("mongoose");
const { md5 } = require("tools-factory-tang/salt");

// 等待值的接收
const get = async ({ curPage, eachPage }) => {
    // 通过位运算符将类型转换为Number类型
    (curPage = ~~curPage), (eachPage = ~~eachPage);
    const data = {
        total: 0,
    }
    // model传一个参数时表示获取这个model对象
    const usersModel = mongoose.model("users");
    // 获取当前model映射的那个集合里面存放的文档总数
    data.total = await usersModel.countDocuments();
    // Math.ceil 向上取整
    data.maxPage = Math.ceil(data.total / eachPage);
    // 计算跳过的条数
    const skipNum = (curPage - 1) * eachPage;
    // find是异步方法，populate(填充(找到相对应的完整数据返回))  skip(跳过多少条). limit(限制范围).exec=execute(执行)  sort({排序条件})
    data.rows = await usersModel.find().populate("carts").skip(skipNum).limit(eachPage).sort({ _id: -1 }).exec();
    // 返回数据给路由
    return data;
}

// 新增用户
const addUsers = async ({
  username,
  password,
  phone,
  site,
  order,
  cartsId,
  coupons
}) => {
  // model传一个参数时表示获取这个model对象
  const usersModel = mongoose.model("users");
  // 添加订单数据
  return await usersModel.create({
    username,
    password,
    phone,
    site,
    order,
    cartsId,
    coupons
  });
};

const findOne = async (_id) => {
  // model传一个参数时表示获取这个model对象
  const usersModel = mongoose.model("users");
  return await usersModel.findOne({ _id });
};

// 删除用户
const removeUsers = async ({ _id }) => {
  const usersModel = mongoose.model("users");
  // remove删除数据库_id匹配的数据
  await usersModel.deleteOne({ _id });
};

//更新用户信息
const update = async (newData) => {
  const usersModel = mongoose.model("users");
  await usersModel.updateOne({ _id: newData._id }, newData);
};

//新增地址
const addSite = async ({ _id, site }) => {
  const usersModel = mongoose.model("users");
  await usersModel.updateOne({ _id: _id }, { $push: { site: site } });
};

//修改地址
const updataSite = async ({ _id, site, index }) => {
  const usersModel = mongoose.model("users");
  const sites = await usersModel.findOne({ _id: _id });
  let newSites = [];
  for (let i = 0; i < sites.site.length; i++) {
    if (i == index) {
      sites.site.splice(index, 1, site);
    }
    newSites.push(sites.site[i]);
  }
  await usersModel.updateOne({ _id: _id }, { $set: { site: newSites } });
};

//新增优惠卷
const addCoupon = async ({ _id, coupons }) => {
  const usersModel = mongoose.model("users");
  await usersModel.updateOne({ _id: _id }, { $push: { coupons: coupons } });
};

//删除优惠卷
const removeCoupon = async ({ _id,couponsId }) => {
  const usersModel = mongoose.model("users");
  // remove删除数据库_id匹配的数据
  const coupons = await usersModel.findOne({ _id: _id });
  let newCoupons = [];
  for (let i = 0; i < coupons.coupons.length; i++) {
    if (coupons.coupons[i] == couponsId) {
        coupons.coupons.splice(i, 1);
    }
    newCoupons.push(coupons.coupons[i]);
  }
  await usersModel.updateOne({ _id: _id }, { $set: { coupons: newCoupons } });
};

//登录
const login = async ({ username, password }) => {
  password = md5(password); //因为注册的时候密码进行了加密处理，登陆时的密码要加密进行比对
  const usersModel = mongoose.model("users");
  //findOne的性能比countDocuments好，findOne找到就返回，而countDocuments要遍历所有的数据
  return await usersModel.findOne({ username, password });
};
//注册
const reg = async ({ username, password, site , phone , cartsId }) => {
  //密码的加密处理
  password = md5(password);
  const usersModel = mongoose.model("users");
  return await usersModel.create({ username, password,site , phone , cartsId });
};

// 暴露接口
module.exports = {
  get,
  addUsers,
  removeUsers,
  findOne,
  update,
  addSite,
  updataSite,
  addCoupon,
  removeCoupon,
  login,
  reg
};
